/**
 * Copyright (c) 2010 Sense Tecnic Systems Inc.
 */
package com.testcase.vincentApp;

import com.testcase.R;

import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Handler;
import android.util.Log;

/**
 * Runnable that reads sensor data from the Android phone and posts it to Sense
 * Tecnic if the user preference to read that sensor is on.
 * 
 * @author Vincent Tsao
 */
class PostSensorDataTask implements Runnable
{
	private Resources resources;
	private SharedPreferences preferences;
	private SensorManager sensorManager;
	private Handler handler;

	/**
	 * Constructor to create a new instance of this runnable.
	 * 
	 * @param resources
	 * @param preferences
	 * @param sensorManager
	 */
	PostSensorDataTask (Resources resources, SharedPreferences preferences, SensorManager sensorManager, Handler handler)
	{
		super ();

		this.resources = resources;
		this.preferences = preferences;
		this.sensorManager = sensorManager;

		this.handler = handler;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Runnable#run()
	 */
	public void run ()
	{
		Log.d (AndroidSensors.TAG, "Reading sensors and updating Sense Tecnic...");

		// get preference keys
		String isLocOnKey = resources.getString (R.string.isLocationOnKey);
		String isAccOnKey = resources.getString (R.string.isAccelerometerOnKey);

		// get preference values
		boolean isLocationOn = preferences.getBoolean (isLocOnKey, true);
		boolean isAccelerometerOn = preferences.getBoolean (isAccOnKey, true);

		// read sensor values and update sense tecnic based on preferences
		if (isLocationOn)
			sensorManager.updateLocation ();

		if (isAccelerometerOn)
			sensorManager.updateAccelerometer ();

		// get the new update interval
		String updateIntervalKey = resources.getString (R.string.updateIntervalKey);
		int updateInterval = Integer.parseInt (preferences.getString (updateIntervalKey, resources.getString (R.string.defaultUpdateInterval)));

		// repost this to emulate a repeating timer
		handler.removeCallbacks (this);
		handler.postDelayed (this, updateInterval);
	}
}
